import React, { useContext, useEffect, useState } from 'react';
import {
  Checkbox,
  Link,
  Modal,
  Space,
  Table,
  TableColumnProps,
  Tooltip,
  Typography,
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { GlobalContext } from '@/context';
import styles from './style/index.module.less';
import { ViolationDetails } from '@/api/interface/violation';
import { Find, findByEmail } from '@/api/modules/violation';
import store from '@/store';
import clipboard from '@/utils/clipboard';
import cs from 'classnames';
import dayjs from 'dayjs';

function RecordFromEmail({
  email,
  visible,
  onVisible,
}: {
  email: string | number;
  visible: boolean;
  onVisible: (violator: boolean) => void;
}) {
  const t = useLocale(locale);
  const { lang, rtl } = useContext(GlobalContext);
  const toDetails = (refNumber) => {
    const searchParams = new URLSearchParams(location.search);
    const fromPath = searchParams.get('fromPath');
    const url = `/${
      fromPath == 'task' ? 'MyTasks' : 'Violation'
    }/Detail?fromPath=${fromPath}&refNumber=${refNumber}`;
    window.open(url, '_blank');
  };
  const columns: TableColumnProps[] = [
    {
      title: t['record.fullName'],
      dataIndex: 'fullName',
      width: 130,
    },
    {
      title: t['record.referenceNumber'],
      dataIndex: 'refNumber',
      width: 220,
      render: (a, b): JSX.Element => {
        return (
          <Link hoverable={false}>
            <Typography.Text underline onClick={() => toDetails(a)}>
              {a}
            </Typography.Text>
            <Typography.Text
              underline
              copyable
              onClick={() => {
                clipboard(a);
                store.dispatch({
                  type: 'update-referenceDetails',
                  payload: {
                    referenceDetails: { refNumber: a, fullName: b.fullName },
                  },
                });
              }}
            ></Typography.Text>
          </Link>
        );
      },
    },
    {
      title: t['record.entityName'],
      dataIndex: 'emirateEntity',
      render: (
        a: { [x: string]: any },
        b: { emirateEntityOther: any }
      ): JSX.Element => {
        const text = a
          ? a[lang === 'en-US' ? 'name' : 'nameAr']
          : b.emirateEntityOther;
        return (
          <Tooltip content={text}>
            <div className="ellipsis">{text || '--'}</div>
          </Tooltip>
        );
      },
    },
    {
      title: t['record.created'],
      dataIndex: 'createdAt',
      render: (x: string | number | Date | dayjs.Dayjs) => (
        <div className="ltr-ipt">{x ? x : '--'}</div>
      ),
      width: 170,
    },
  ];

  const [loading, setLoading] = useState<boolean>(false);
  const [list, setList] = useState<Array<ViolationDetails>>([]);

  const getOtherList = () => {
    setLoading(true);
    findByEmail({ email: email })
      .then((res) => {
        setList(res.data);
        setLoading(false);
      })
      .catch(() => {
        setLoading(true);
      });
  };
  useEffect(() => {
    if (email && visible) {
      getOtherList();
      return;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, email]);

  return (
    <div>
      <Modal
        style={{ width: '860px' }}
        visible={visible}
        onCancel={() => onVisible(false)}
        maskClosable={false}
        unmountOnExit={true}
        footer={null}
        className={cs(styles['record-modal'], rtl ? 'rtl' : '')}
      >
        <div>
          <div className={styles['recoed']}>
            <Space>
              {t['recordFromEmail']}
              <span className={styles['record-span']}> {email}</span>
            </Space>
          </div>
          <div className={styles['record-modal-scroll']}>
            <Table
              loading={loading}
              columns={columns}
              data={list}
              pagination={false}
              border={{ headerCell: true, wrapper: true }}
              rowKey="id"
            ></Table>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default RecordFromEmail;
